package com.google.code.head2head.gwtmodules.server;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.gwtwidgets.client.util.Location;
import org.gwtwidgets.client.util.WindowUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.code.head2head.constants.SessionRequestConstants;
import com.google.code.head2head.model.Entry;
import com.google.code.head2head.service.EntryService;

@SuppressWarnings("serial")
public class FileUploadServlet extends HttpServlet {

	private WebApplicationContext ctx;
	private EntryService entryService;
	private Logger LOG = Logger.getLogger(FileUploadServlet.class);

	@Override
	public void init() throws ServletException {
		ctx = WebApplicationContextUtils
				.getWebApplicationContext(getServletContext());
		entryService = (EntryService) ctx.getBean("entryService");
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {

			// creates the new entry
			Entry entry = new Entry();

			// adds the ip adress of the user
			Set<String> ips = new HashSet();
			String ip = request.getRemoteAddr();
			ips.add(ip);
			entry.setIps(ips);

			// persists the entry
			entryService.create(entry);
			
			//puts the id in session scope
			request.getSession().setAttribute(SessionRequestConstants.ENTRYID.name(), entry.getId());

			// creates the directory for the new entry
			File entryDirectory = new File(getServletContext().getRealPath(
					entryService.getEntriesImagesDirectory())
					+ "/" + entry.getId());
			entryDirectory.mkdir();

			// sets images address
			entry.setFistImageUrl(entryService.getEntriesImagesDirectory()
					+ "/" + entry.getId() + "/image1.jpg");
			entry.setSecondImageUrl(entryService.getEntriesImagesDirectory()
					+ "/" + entry.getId() + "/image2.jpg");

			// updates the entry with images address
			entryService.update(entry);

			// Create a factory for disk-based file items
			FileItemFactory factory = new DiskFileItemFactory();

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			// Parse the request
			List items = upload.parseRequest(request);

			// creates a list of file items
			for (Iterator iterator = items.iterator(); iterator.hasNext();) {
				FileItem item = (FileItem) iterator.next();
				if (item.getFieldName().equals("image1")) {
					File uploadedFile1 = new File(getServletContext()
							.getRealPath(
									entryService.getEntriesImagesDirectory())
							+ "/" + entry.getId() + "/image1.jpg");
					item.write(uploadedFile1);
				} else if (item.getFieldName().equals("image2")) {
					File uploadedFile2 = new File(getServletContext()
							.getRealPath(
									entryService.getEntriesImagesDirectory())
							+ "/" + entry.getId() + "/image2.jpg");
					item.write(uploadedFile2);
				}
			}

			// returns a message to the client
			response.getWriter().write("File uploaded");

		} catch (Exception e) {
			LOG.error(e.getMessage() + e.getCause());
			e.printStackTrace();
			response.getWriter().write(
					"Problem during file upload : " + e.getMessage());
		}
	}

}
